# services/group_db_service.py
from typing import Optional
from sqlalchemy import func
from sqlalchemy import select
from sqlalchemy.ext.asyncio.session import AsyncSession

from common.sqlalchemy_db import SqlalchemyX
from modules.mod import Group


class GroupDBService:
    def __init__(self, session: AsyncSession = SqlalchemyX.AsyncSessionLocal()):
        self.session = session

    async def check_group_exists(self, filters: dict) -> bool:
        count_query = select(func.count()).select_from(Group).filter_by(**filters)
        result = await self.session.execute(count_query)
        return result.scalar() > 0

    async def get_default_group(self) -> Optional[Group]:
        query = select(Group).filter(Group.group_type == 0)
        result = await self.session.execute(query)
        group = result.scalars().first()
        if not group:
            raise ValueError("未找到默认群组")
        return group

    async def create_group(self, db: AsyncSession, data: dict) -> Group:
        g = Group(**data)
        db.add(g)
        await db.commit()
        return g

    async def get_group_by(self, filters: dict) -> Optional[Group]:
        repo  = select(Group).filter_by(**filters)
        result = await self.session.execute(repo)
        return result.scalar()

    async def get_group_mes(self, option: dict) -> Group:
        query = select(Group).filter_by(**option)
        result = await self.session.execute(query)
        group = result.scalars().first()

        if not group:
            raise ValueError(f"未找到符合条件的群组: {option}")

        return group
